<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Register extends Public_Controller
{
	public function __construct()
	{
		parent::__construct();
		$userData = $this->session->all_userData();
		if (isset($userData['logged_in']) && $userData['logged_in']){
			redirect('./');
		}
		$this->load->model('uploking_users_m');
		$this->load->model('email_templates_m');
		$this->load->library(array('keywords/keywords'));
		$this->load->library('form_validation');
		$this->lang->load('uploking');
		$this->load->helper('uploking');
		$this->load->helper('geoiploc');
		$this->validation_rules = array(
			array(
				'field' => 'first_name',
				'label' => 'lang:uploking_home_first_name_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'last_name',
				'label' => 'lang:uploking_home_last_name_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'username',
				'label' => 'lang:uploking_home_username_label',
				'rules' => 'trim|required|max_length[255]|min_length[6]|is_unique[uploking_users.username]'
			),
			array(
				'field' => 'email',
				'label' => 'lang:uploking_home_email_label',
				'rules' => 'trim|required|max_length[255]|is_unique[uploking_users.email]'
			),
			array(
				'field' => 'password',
				'label' => 'lang:uploking_home_password_label',
				'rules' => 'trim|required|max_length[255]|min_length[6]|matches[retype_password]'
			),
			array(
				'field' => 'retype_password',
				'label' => 'lang:uploking_home_retype_password_label',
				'rules' => 'trim|required|max_length[255]'
			),
		);
	}

	// blog/page/x also routes here
	public function index()
	{
		$this->form_validation->set_rules($this->validation_rules);
		if ($this->form_validation->run()){
			$password = $this->input->post('password');
			$plainPassword = $password;
			$active_code = $this->generate_code();
			$pin = $this->generate_pin();
			$ip = $this->input->ip_address();
			$this->uploking_users_m->insert(array(
				'first_name'	=> $this->input->post('first_name'),
				'last_name'	=> $this->input->post('last_name'),
				'username'	=> $this->input->post('username'),
				'email'	=> $this->input->post('email'),
				'pin'	=> $pin,
				'ip'	=> $ip,
				'country_name'	=> getCountryFromIP($ip, " NamE "),
				'country_code'	=> getCountryFromIP($ip, "code"),
				'password'	=> md5($password),
				'created_time'	=> time(),
				'active_code'	=> $active_code,
				'active'	=> 0
			));
			
			$emailTemplate = $this->email_templates_m->get_by('slug', ACTIVE_ACCOUNT_EMAIL_TEMPLATE_SLUG);
			$this->load->library('email');
			$this->email->from( $this->settings->get('server_email'), lang('uploking_profile_active_account_email_name_label'));
			$this->email->to($this->input->post('email'));
			$this->email->subject($emailTemplate->subject);
			$emailTemplate->body = str_replace('###ACTIVE_LINK###', '<a href="'.site_url().'account/register/active/'.$active_code.'">'.lang('uploking_click_here_text').'</a>', $emailTemplate->body);
			$emailTemplate->body = str_replace('###PIN###', $pin, $emailTemplate->body);
			$emailTemplate->body = str_replace('###LASTNAME###', $this->input->post('last_name'), $emailTemplate->body);
			$emailTemplate->body = str_replace('###FIRST_NAME###', $this->input->post('first_name'), $emailTemplate->body);
			$emailTemplate->body = str_replace('###EMAIL###', $this->input->post('email'), $emailTemplate->body);
			$emailTemplate->body = str_replace('###PASSWORD###', $plainPassword, $emailTemplate->body);
			
			$this->email->message($emailTemplate->body);
			//$this->email->message('Thank you for registering new account<br/>. Please <a href="'.site_url().'account/register/active/'.$active_code.'">click here</a> to active your account');
			
			$this->email->send();
			
			$this->template
			->title($this->module_details['name'])
			->build('register_success', $this->data);
		}else{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$user->$field['field'] = set_value($field['field']);
			}
			$this->template
			->title($this->module_details['name'])
			->set('user', $user)
			->build('register', $this->data);
		}
		
	}
	public function active($activeCode = ''){
		$user = $this->uploking_users_m->get_by('active_code', $activeCode);
		if($user){
			if(!$user->active){
				$this->uploking_users_m->update($user->id, array('active' => 1));
			}
		}
		$this->template
			->title($this->module_details['name'])
			->set('user', $user)
			->build('active', $this->data);
	}
	public function generate_code(){
		$length = 18;
		$validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ1234567890";
		$validCharNumber = strlen($validCharacters);
		$result = "";
		for ($i = 0; $i < $length; $i++) {
			$index = mt_rand(0, $validCharNumber - 1);
			$result .= $validCharacters[$index];
		}
		if($this->_check_code($result)){
			return $result;
		}else{
			$this->generate_code();
		}
	}
	public function _check_code($code)
	{
		if($this->uploking_users_m->get_by('active_code', $code)){
			return false;
		}else{
			return true;
		}
	}
	public function generate_pin($length = 4){
		$validCharacters = "1234567890";
		$validCharNumber = strlen($validCharacters);
		$result = "";
		for ($i = 0; $i < $length; $i++) {
			$index = mt_rand(0, $validCharNumber - 1);
			$result .= $validCharacters[$index];
		}
		if($this->_check_pin($result)){
			return $result;
		}else{
			$this->generate_code();
		}
	}
	public function _check_pin($pin)
	{
		if($this->uploking_users_m->get_by('pin', $pin)){
			return false;
		}else{
			return true;
		}
	}
}
